package com.huike.pmps.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huike.pmps.dao.NewSignDao;
import com.huike.pmps.model.constants.GlobalConstants;
import com.huike.pmps.model.dto.common.PageInfo;
import com.huike.pmps.model.entity.NewSign;
import com.huike.pmps.model.entity.Provinces;
import com.huike.pmps.model.entity.Region;
import com.huike.pmps.model.vo.PageResult;
import com.huike.pmps.model.vo.Result;
import com.huike.pmps.service.DictionaryService;
import com.huike.pmps.service.NewSignService;
import com.huike.pmps.service.ProvincesService;
import com.huike.pmps.service.RegionService;
import com.huike.pmps.utils.PmpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 作者：谌贵斌(黑桃K)
 * 日期: 2888-08-08
 * 老师QQ: 272488352
 * 官方QQ交流群: 377748272
 * 刀客程序员官网：http://www.daoke360.com
 * 刀客程序员淘宝旗舰店：https://daoke360.taobao.com/
 */
@Service
@Slf4j
public class NewSignServiceImpl implements NewSignService {

    @Autowired
    NewSignDao newSignDao;
    @Autowired
    RegionService regionService;
    @Autowired
    ProvincesService provincesService;
    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public Result insertByImportNewSignService(MultipartFile file) {
        if (file.isEmpty()) {
            return Result.failure("文件为空");
        }
        int count = 0;
        try {
            //根据路径获取这个操作excel的实例
            XSSFWorkbook wb = new XSSFWorkbook(file.getInputStream());
            //根据页面index 获取sheet页
            XSSFSheet sheet = wb.getSheetAt(0);
            //获取标题行
            XSSFRow titleRow = sheet.getRow(0);
            String[] titleRowArray = new String[]{"对应客户", "合同标题", "合同总金额", "业绩金额", "负责人", "合同编号", "产品品类", "所属部门", "战区", "业绩时间", "月份", "周", "财年"};
            for (int i = 0; i < titleRowArray.length; i++) {
                if (!titleRowArray[i].equals(titleRow.getCell(i).getStringCellValue()))
                    return Result.failure("模板标题行已被修改，请勿修改供应商模板标题行");
            }
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            List<NewSign> newSignList = new ArrayList<>();
            XSSFRow row = null;
            Date date = new Date();
            for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
                //获取每一行数据
                count++;
                row = sheet.getRow(i);
                if (row.getCell(8) != null && row.getCell(8).toString().contains("VLOOKUP"))
                    return Result.success("表格中不允许含有公式，本次导入全部失败");


                //对应客户
                if (row.getCell(0) == null || StringUtils.isBlank(row.getCell(0).toString()))
                    return Result.failure("本次导入全部失败，第【" + i + "】条数据 对应客户 为空");
                String customerName = row.getCell(0).toString();

                //合同标题
                if (row.getCell(1) == null || StringUtils.isBlank(row.getCell(1).toString()))
                    return Result.failure("本次导入全部失败，第【" + i + "】条数据 合同标题 为空");
                String contractTitle = row.getCell(1).toString();

                //合同总金额
                if (row.getCell(2) == null || StringUtils.isBlank(row.getCell(2).toString()))
                    return Result.failure("本次导入全部失败，第【" + i + "】条数据 合同标题 为空");
                BigDecimal contractAmount = BigDecimal.valueOf(Double.valueOf(row.getCell(2).toString()));


                //业绩金额
               /* if (row.getCell(3) == null || StringUtils.isBlank(row.getCell(3).toString()))
                    return Result.failure("本次导入全部失败，第【" + i + "】条数据 业绩金额 为空");*/
                BigDecimal financialAmount = row.getCell(3) == null || StringUtils.isBlank(row.getCell(3).toString()) ? null : BigDecimal.valueOf(Double.valueOf(row.getCell(3).toString()));

                //负责人
               /* if (row.getCell(4) == null || StringUtils.isBlank(row.getCell(4).toString()))
                    return Result.failure("本次导入全部失败，第【" + i + "】条数据 负责人 为空");*/
                String chargeName = row.getCell(4) == null || StringUtils.isBlank(row.getCell(4).toString()) ? null : row.getCell(4).toString();

                //合同编号
               /* if (row.getCell(5) == null || StringUtils.isBlank(row.getCell(5).toString()))
                    return Result.failure("本次导入全部失败，第【" + i + "】条数据 合同编号 为空");*/
                String contractNo = row.getCell(5) == null || StringUtils.isBlank(row.getCell(5).toString()) ? null : row.getCell(5).toString();

                //产品品类
                Integer productTypeId = null;
                String productTypeName = null;
                if (row.getCell(6) == null || StringUtils.isBlank(row.getCell(6).toString()))
                    return Result.failure("本次导入全部失败，第【" + i + "】条数据 产品品类 为空");
                else {
                    productTypeName = row.getCell(6).toString();
                    if (productTypeName.contains("在线资源建设和运营服务") || productTypeName.contains("基于高校邦的课程运营服务") || productTypeName.contains("高校邦运营服务")) {
                        productTypeId = 1;
                        productTypeName = redisTemplate.opsForHash().get(GlobalConstants.REDIS_HASH_DICTIONARY_DATA, 1).toString();
                    }
                    if (productTypeName.contains("在线学习平台产品") || productTypeName.contains("精品在线开放课程产品")) {
                        productTypeId = 2;
                        productTypeName = redisTemplate.opsForHash().get(GlobalConstants.REDIS_HASH_DICTIONARY_DATA, 2).toString();
                    }
                    if (productTypeName.contains("在线资源内容产品") || productTypeName.contains("课程拍摄与制作服务")) {
                        productTypeId = 3;
                        productTypeName = redisTemplate.opsForHash().get(GlobalConstants.REDIS_HASH_DICTIONARY_DATA, 3).toString();
                    }
                    if (productTypeName.contains("在线资源内容产品") || productTypeName.contains("高校邦学习平台")) {
                        productTypeId = 4;
                        productTypeName = redisTemplate.opsForHash().get(GlobalConstants.REDIS_HASH_DICTIONARY_DATA, 4).toString();
                    }
                }
                //省区和战区
                Integer regionId, provinceId = null;
                String regionName, provinceName = null;
                if (row.getCell(7) == null || StringUtils.isBlank(row.getCell(7).toString())) {
                    return Result.success("本次导入全部失败，第" + i + "条数据,省份为空，本次导入全部失败");
                } else {
                    Provinces provinces = provincesService.selectByProvinceName(row.getCell(7).toString());
                    if (provinces != null) {
                        provinceId = provinces.getProvinceId();
                        provinceName = provinces.getProvince();
                    } else {
                        return Result.success("本次导入全部失败，第" + i + "条数据,省份数据填写有误,请按规则填写");
                    }
                }
                if (row.getCell(8) == null || StringUtils.isBlank(row.getCell(8).toString())) {
                    return Result.success("本次导入全部失败，第" + i + "条数据,战区为空，本次导入全部失败");
                } else {
                    Region region = regionService.selectOneByRegionName(row.getCell(8).toString().substring(0, 2));
                    if (region != null) {
                        regionId = region.getId();
                        regionName = region.getRegion();
                    } else {
                        return Result.success("本次导入全部失败，第" + i + "条数据,战区数据填写有误,请按规则填写");
                    }
                }
                //业绩时间
                if (row.getCell(9) == null || StringUtils.isBlank(row.getCell(9).toString()))
                    return Result.success("本次导入全部失败，第" + i + "条数据,业绩时间，本次导入全部失败");
                Date performanceDate = row.getCell(9).getDateCellValue();
                Integer year = PmpUtil.getDateInfo(performanceDate, GlobalConstants.YEAR);
                Integer weekOfYear = PmpUtil.getDateInfo(performanceDate, GlobalConstants.WEEK_OF_YEAR);
                Integer seasonOfYear = PmpUtil.getDateInfo(performanceDate, GlobalConstants.SEASON);
                Integer monthOfYear = PmpUtil.getDateInfo(performanceDate, GlobalConstants.MONTH);

                //月份
                Integer month = monthOfYear; //row.getCell(10) == null || StringUtils.isBlank(row.getCell(10).toString()) ? null : Double.valueOf(row.getCell(10).toString()).intValue();
                //周
                Integer week = PmpUtil.getDateInfo(performanceDate, GlobalConstants.WEEK_OF_MONTH);// row.getCell(11) == null || StringUtils.isBlank(row.getCell(11).toString()) ? null : Double.valueOf(row.getCell(11).toString()).intValue();


                //所属财年
                Integer financialYear = null;
                if (row.getCell(12) != null && StringUtils.isNotBlank(row.getCell(12).toString())) {
                    if (row.getCell(12).toString().startsWith("FY") && row.getCell(12).toString().endsWith("19")) {
                        financialYear = 2019;
                    } else if (row.getCell(12).toString().startsWith("FY") && row.getCell(12).toString().endsWith("20")) {
                        financialYear = 2020;
                    } else if (row.getCell(12).toString().startsWith("FY") && row.getCell(12).toString().endsWith("21")) {
                        financialYear = 2021;
                    } else if (row.getCell(12).toString().startsWith("FY") && row.getCell(12).toString().endsWith("22")) {
                        financialYear = 2022;
                    } else {
                        financialYear = 2020;
                    }
                }
                NewSign newSign = NewSign.builder().customerName(customerName).contractNo(contractNo).contractTitle(contractTitle)
                        .contractAmount(contractAmount).chargeName(chargeName).financialAmount(financialAmount).regionId(regionId)
                        .regionName(regionName).provinceId(provinceId).provinceName(provinceName).performanceDate(performanceDate)
                        .year(year).month(month).week(week).financialYear(financialYear).productTypeId(productTypeId).productTypeName(productTypeName)
                        .weekOfYear(weekOfYear).seasonOfYear(seasonOfYear).monthOfYear(monthOfYear).createTime(date)
                        .build();
                newSignList.add(newSign);
            }
            if (newSignList.size() > 0) {
                newSignDao.insertBatchList(newSignList);
                return Result.success("全部导入成功");
            } else {
                return Result.failure("表格中没有数据");
            }
        } catch (IOException e) {
            e.printStackTrace();
            return Result.failure("本次导入全部失败，读取表格数据异常" + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.success("本次导入全部失败，第" + count + "条数据解析异常");
        }
    }

    @Override
    public Result selectByCondition(PageInfo pageInfo, Integer regionId, Integer provinceId, String contractTitle, Integer year, Integer month) {
        QueryWrapper<NewSign> queryWrapper = new QueryWrapper<>();
        if (regionId != null)
            queryWrapper.eq("region_id", regionId);

        if (provinceId != null)
            queryWrapper.eq("province_id", provinceId);

        if (StringUtils.isNotBlank(contractTitle))
            queryWrapper.eq("contract_title", contractTitle);

        if (year != null)
            queryWrapper.eq("year", year);

        if (month != null)
            queryWrapper.eq("month", month);

        Page<NewSign> page = new Page<>(pageInfo.getPage(), pageInfo.getPageSize());
        Page<NewSign> pageList = newSignDao.selectPage(page, queryWrapper);
        if (pageList.getSize() > 0) {
            PageResult pageResult = PageResult.builder().pageNumber(pageList.getCurrent()).pageSize(pageList.getSize())
                    .total(pageList.getTotal()).rows(pageList.getRecords()).build();
            return Result.success(pageResult);
        } else {
            return Result.success("没有符合条件的记录");
        }
    }
}
